package com.yycx.module.system.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.module.system.client.entity.SysDevice;
import com.yycx.module.system.client.entity.SysOperationLog;
import com.yycx.module.system.provider.mapper.SysDeviceMapper;
import com.yycx.module.system.provider.service.SysDeviceService;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.module.system.provider.service.SysOperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.yycx.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备接口实现类
 *
 * @author flyme
 * @date 2024-07-07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysDeviceServiceImpl extends BaseServiceImpl<SysDeviceMapper, SysDevice> implements SysDeviceService {

    @Autowired
    private SysOperationLogService operationLogService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, SysDevice device, EntityMap extra) {
        return ResultBody.ok();
    }

    @Override
    public SysDevice checkDeviceNo(String deviceNo) {
        LambdaQueryWrapper<SysDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, SysDevice::getDeviceNo, deviceNo);
        SysDevice sysDevice = getOne(wrapper, false);
        if (FlymeUtils.isEmpty(sysDevice)) {
            SysOperationLog sysOperationLog = operationLogService.findByBusId(deviceNo);
            if (FlymeUtils.isEmpty(sysOperationLog)) {
                sysOperationLog = new SysOperationLog();
                sysOperationLog.setBizId(deviceNo);
            }
            sysOperationLog.setBizType("SysDevice");
            sysOperationLog.setMsg("非法设备请求");
            operationLogService.saveOrUpdate(sysOperationLog);
        }
        return sysDevice;
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<SysDevice> cq, SysDevice device, EntityMap requestMap) {
        cq.orderByDesc("device.createTime");
        cq.like(SysDevice.class, "deviceNo");
        cq.eq(SysDevice.class, "state");
        cq.eq(SysDevice.class, "companyId");
        return ResultBody.ok();
    }
}
